import React, { useEffect, useMemo, useState } from 'react'
import Taro, { usePullDownRefresh } from '@tarojs/taro'
import QRCode from '@/utils/weapp-qrcode.js'
import {RoundNum} from '@/utils/helper'
import {View,Image,Text} from '@tarojs/components'
import './index.scss'

export default function OrderDetail() {
  const orderStr = {
    WaitPay:'等待支付',
    PaySuccess:'支付成功',
    TicketSuccess:'出票成功',
    TicketFailed:'出票失败',
    RefundAmountSuccess:'退款成功',
    AutoRefundAmountSuccess:'自动退款成功',
    RefundSuccess:'退款退票成功',
    AutoRefundSuccess:'自动退款退票成功'
  }
  const [curTabs,setCurTabs] = useState(0)
  const [codeImg,setCodeImg] = useState(null)
  const [info,setInfo] = useState({})
  const [rebook,setRebook] = useState({})
  const [cinemaInfo,setCinemaInfo] = useState({})
  useEffect(()=>{
    _initData()
  },[])
  usePullDownRefresh(()=>{
    _initData()
    Taro.stopPullDownRefresh()
  })
  const _initData =e=>{
    Taro.showLoading({title:'加载中...'})
    Taro.$get('/cinema-app/api/v1/order/goods',{orderId:Taro.getCurrentInstance().router.params.id},'1').then(res=>{
      if(res.code == '1'){
        setInfo(res.content)
        Taro.$post('/cinema-app/api/v1/refund/byCinemaId',{
          "cinemaId": res.content?.cinemaId,
          "showTimeStart":res.content?.showTimeStart
        }).then(ret=>{
          setRebook(ret.content)
        })
        Taro.$get('/cinema-app/api/v1/cinema/detail',{
          cinemaId:res.content?.cinemaId,
          latitude:res.content?.cinemaLatitude,
          longitude:res.content?.cinemaLongitude
        }).then(ret=>{
          setCinemaInfo(ret.content)
        })
        Taro.setNavigationBarTitle({
          title:res.content.orderType=='Ticket'?orderStr[res.content.status]:'小食订单'
        })
        if(res.content.orderType == 'Ticket'){
          setCodeImg(QRCode.drawImg(res.content.printNo, {
            size: 160
          }))
          return;
        }
        if(res.content.goodsPrintNo){
          setCodeImg(QRCode.drawImg(res.content.goodsPrintNo, {
            size: 160
          }))
        }
      }else{
        Taro.$toast(res.message)
        setTimeout(() => {
          Taro.navigateBack()
        }, 1000);
      }
    })
  }
  let calcPrice = useMemo(()=>{
    let price = 0;
    info.ticketList?.map(res=>{
      price += (res.ticketPrice*1)
    })
    return RoundNum(price) || 0
  },[info])
  return (
    <View className='order-detail'>
      <View className="detail-main">
        {info.status == 'RefundSuccess'?<View className="main-refund">
          <View>{info.returdTime} 已退款，退款金额：{info.payAmount}元</View>
          钱款已通过支付方式原路退回。
        </View>:null}
        <View className="main-address">
          <View className="address-title" onClick={()=>{
            Taro.navigateTo({
              url:'/mainPages/select-cinema/index'
            })
          }}>
            <View className='box-flex' style={{alignItems:'center'}}><View className="dot h2">{info.cinemaName} </View><Text className='at-icon at-icon-chevron-right'></Text></View>
            <View className='dot' style={{fontSize:10}}>{info.cinemaAddress}</View>
          </View>
          <Image src={require('@/images/common/position.svg')} mode='widthFix' onClick={()=>{
            Taro.openLocation({
              latitude: (info.cinemaLatitude*1),
              longitude: (info.cinemaLongitude*1),
              scale: 18,
              name:info.cinemaName,
              address:info.cinemaAddress,
            })
          }}></Image>
          {cinemaInfo.contactPhone?
          <Image onClick={()=>{
            Taro.makePhoneCall({
              phoneNumber:cinemaInfo.contactPhone
            })
          }} src={require('@/images/common/call.svg')} mode='widthFix'></Image>:null}
        </View>
        
        <View className="main-box">
          <View className="goods-list">
            {info.goodsViewList?.map(res=>{
              return <View className="list-item">
              <Image src={res.imageUrl} mode='aspectFill' className='item-img'></Image>
              <View className="item-info">
                <View className="h2 dot2">{res.goodsName}</View>
                <View className="sub-h2">{res.goodsDesc}</View>
              </View>
              <View className="info-price">
                <View className="price-left">实付 ￥{res.payAmount}</View>
                <View className="price-num price-del">￥{res.goodsPrice}</View>
                <Text className="price-num">x {res.goodsCount}</Text>
              </View>
            </View>
            })}
          </View>
        </View>

        {info.status!='WaitPay'?
        <View className="main-code">
          <View className='code-title'>凭「取餐码」在柜台取餐</View>
          <View className={`detail-ticket ${info.status == 'RefundSuccess' || info.planPass?'opacity':''}`}>
            <View className="list-item">
              <View className="item-canvas">
                <Image src={codeImg} className='item-img' />
                {info.status == 'RefundSuccess'?<Image src={require('@/images/common/refund.svg')} className='canvas-icon'></Image>:null}
                {info.planPass?<Image src={require('@/images/common/shown.svg')} className='canvas-icon'></Image>:null}
              </View>
              <View className="item-code">
                {info.goodsPrintNo?<View className="box-flex">取餐码： <Text style={{color:'#26282A'}}>{info.goodsPrintNo}</Text></View>:null}
                {info.goodsVerifyCode?<View className="box-flex">验票码： <Text style={{color:'#26282A'}}>{info.goodsVerifyCode}</Text></View>:null}
              </View>
            </View>
          </View>
        </View>:null}
        {info.isDisplayRefund?
        <View className="main-rebook">
          <View className="rebook-title">退小食</View>
          <View className="rebook-list">
            <View className="list-item">
              <View className="item-title">
                <View style={{fontSize:14,color:'#07C160'}} className="at-icon at-icon-check-circle"></View>
                <View className="h2">支持退小食</View>
                <View className='at-icon at-icon-chevron-right'></View>
              </View>
              <View className="item-info">
                <View className="info-p">未过期且未兑换可支持退款</View>
                <View className="info-button" onClick={()=>{
                  Taro.navigateTo({
                    url:`/mineSubPack/foods-return/index?id=${info.id}`
                  })
                }}>退小食</View>
              </View>
            </View>
          </View>
        </View>:null}

        <View className="detail-intro">
          <View className="intro-title">订单详情
            {/* <View className="title-span">结算明细 <Text className='at-icon at-icon-chevron-right'></Text></View> */}
          </View>
          <View className="intro-list">
            <View className="list-item">
              <View className="item-label">实付金额</View>
              ￥{info.payAmount}
            </View>
            <View className="list-item">
              <View className="item-label">订单编号</View>
              {info.id} 
              <View className="item-copy" onClick={()=>{
                Taro.setClipboardData({
                  data:info.id,
                  success:res=>{
                    Taro.$toast('复制成功')
                  }
                })
              }}><Image src={require('@/images/common/copy.svg')} mode='widthFix'></Image> 复制</View>
            </View>
            <View className="list-item">
              <View className="item-label">购买时间</View>
              {info.createTime}
            </View>
            <View className="list-item">
              <View className="item-label">支付方式</View>
              {info.payMethod || '微信支付'}
            </View>
          </View>
        </View>

        <View className="detail-notice">
          <View className="notice-title">使用须知</View>
          <View className="notice-p">1.本单发票由影院提供，详情请咨询影院。</View>
          <View className="notice-p">2.营业时间内可用，仅限卖品柜台自取。</View>
        </View>
      </View>
    </View>
  )
}
